import http from 'wechat-http'
import { setStorage } from './storage'
// 接口基础地址
http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = (options) => {
  // 合并头信息
  options.header = {
    // 权限认证
    Authorization: `Bearer ${wx.getStorageSync('token')}`,
    // 默认头信息
    ...options.header,
  }
  // 拦截器处理后的请求参数
  return options
}

// 响应拦截器
http.intercept.response = async ({ statusCode, data, config }) => {
  const refreshToken = wx.getStorageSync('refreshToken')
  if (data.code === 401 && config.url.includes(`${refreshToken}`)) {
    console.log(getCurrentPages()[0].route)
    wx.redirectTo({
      url: `/pages/login/index?redirectURl=${getCurrentPages()[0].route}`,
      success: function () {
        console.log('跳转成功')
      },
      fail: function () {
        console.log('跳转失败')
      },
      complete: function () {
        // complete
      },
    })
  }
  if (data.code === 401 && refreshToken) {
    console.log(refreshToken)
    const { data } = await wx.http.post('/refreshToken', {
      header: {
        Authorization: `Bearer ${refreshToken}`,
      },
    })
    setStorage('token', data.token)
    const { header } = config
    header.Authorization = `Bearer ${data.token}`
    http(config)
  }
  if (statusCode === 500) return wx.utils.toast('服务器端异常')

  if (statusCode === 502) return wx.utils.toast('服务器端正在部署，请稍等')
  // 拦截器处理后的响应结果
  return data
}

// 作为模块导出
export default http

// 也可挂载到 wx 全局命名空间
wx.http = http
